package com.ex.managersystem1024.controller;


import cn.hutool.core.io.FileUtil;
import com.ex.managersystem1024.common.Result;
import com.ex.managersystem1024.entity.StockFile;
import com.ex.managersystem1024.mapper.FileMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;


@RestController
@RequestMapping("/file")
@Api(value = "File Controller", tags = { "文件相关接口" })
public class FileController {

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    @Resource
    private FileMapper fileMapper;

    private static final String ROOT_PATH =  System.getProperty("user.dir") + File.separator + "files";


    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        // 文件的原始名称
        String originalFilename = file.getOriginalFilename();
        String fileName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);
        }
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + fileName + "." + extName;
        }
        //存储文件到磁盘
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);
        String url = "http://" + ip + ":" + port + "/file/download/" + originalFilename;
        //上传文件记录入库
        StockFile stockFile = StockFile.builder()
                .filename(originalFilename)
                .filesize(file.getSize())
                .createdAt(new Date())
                .build();
        fileMapper.insert(stockFile);
        return Result.success(url);
    }


    /**
     * 文件下载
     * @param fileName
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "文件下载")
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        String filePath = ROOT_PATH  + File.separator + fileName;
        if (!FileUtil.exist(filePath)) {
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

}
